#include <iostream>
#include <queue>
#include <cstring>

using namespace std;
const int N = 1010;
typedef pair<int, int> pii;
int n, m;
int p[N][N];
bool st[N][N];

int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};

bool bfs(int mid)
{
    if(n == 1) return true;
    memset(st , 0 , sizeof st);

    queue<pii>q;
    for(int j = 1;j <= m;j ++)
    {
        q.push({1 , j});
        st[1][j] = true;
    }
    while(q.size())
    {
        auto t = q.front(); q.pop();
        int x = t.first , y = t.second;
        for(int k = 0;k < 4;k ++)
        {
            int a = dx[k] + x , b = dy[k] + y;
            if(a >= 1 && a <= n && b >= 1 && b <= m && p[a][b] <= mid &&st[a][b] == false)
            {
                st[a][b] = true;
                q.push({a , b});
                if(a == n) return true;
            }
        }
    }
    return false;
}
int main()
{
    cin >> n >> m;
    int l = 0 , r = 0;
    for(int i = 1;i <= n;i ++)
    {
        for(int j = 1;j <= m;j ++)
        {
            cin >> p[i][j];
            r = max(r , p[i][j]);
        }
    }

    while(l < r)
    {
        int mid = (l + r) / 2;
        if(bfs(mid)) r = mid;
        else l = mid + 1;
    }
    cout << l << endl;
    return 0;
}